package com.meida.module.product.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.query.CriteriaDelete;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.module.product.client.entity.ProdProductGroup;
import com.meida.module.product.provider.mapper.ProdGroupProductMapper;
import com.meida.module.product.provider.service.ProdGroupProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 店铺产品分类和产品中间表 实现类
 *
 * @author flyme
 * @date 2019-07-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProdGroupProductServiceImpl extends BaseServiceImpl<ProdGroupProductMapper, ProdProductGroup> implements ProdGroupProductService {


    @Override
    public Boolean setProductGroup(Long productId, String[] groupIds) {
        if (ObjectUtils.isNotNull(productId, groupIds)) {
            List<ProdProductGroup> prodGroupProducts = new ArrayList<>();
            for (String groupId : groupIds) {
                ProdProductGroup prodGroupProduct = new ProdProductGroup();
                prodGroupProduct.setProductId(productId);
                prodGroupProduct.setGroupId(Long.parseLong(groupId));
                prodGroupProducts.add(prodGroupProduct);
            }
            return saveBatch(prodGroupProducts);
        } else {
            return false;
        }
    }

    @Override
    public Boolean delProductGroup(Long productId) {
        if (ObjectUtils.isNotNull(productId)) {
            CriteriaDelete cd = new CriteriaDelete();
            cd.eq("productId", productId);
            return remove(cd);
        } else {
            return false;
        }
    }

    @Override
    public List<Long> selectIds(Long productId) {
        CriteriaQuery cq = new CriteriaQuery(ProdProductGroup.class);
        cq.select("groupId");
        cq.eq(true, "productId", productId);
        return listObjs(cq, e -> new Long(e.toString()));
    }

    @Override
    public int countByGroupId(Long groupId) {
        CriteriaQuery cq = new CriteriaQuery(ProdProductGroup.class);
        return count(cq.eq(true, "groupId", groupId));
    }
}
